import java.util.*;


public class FeedParser {
	ArrayList<String> items=new ArrayList<String>();
	ArrayList<String> titles=new ArrayList<String>();
	ArrayList<String> dates=new ArrayList<String>();
	ArrayList<String> sisu=new ArrayList<String>();
	ArrayList<String> links=new ArrayList<String>();
	ArrayList<ArrayList<String>> all = new ArrayList<ArrayList<String>>();
	String curLink = "";
	String fullTxt;
	int cur = 0;
	public FeedParser(String html){
		// TEEME XML-ist (STRING) DOCUMENT
		fullTxt = html;
		all.add(items);
		all.add(titles);
		all.add(dates);
		all.add(sisu);
		all.add(links);
		
		while (cur>=0) {
			String item = getTagContent(fullTxt, "item");
			items.add(item);
			if (cur < 0) break;
			fullTxt=fullTxt.substring(cur);
			titles.add(removeTags(getTagContent(item, "title")));
			dates.add(removeTags(getTagContent(item, "pubDate")));
			sisu.add(removeTags(getTagContent(item, "description")));
			links.add(curLink);
		} 
		
		//for (Object lines : items) System.out.println(lines);
		//for (Object lines : titles) System.out.println(lines);
		//for (Object lines : dates) System.out.println(lines);
		//for (Object lines : sisu) System.out.println(lines);		
		
	}
	String getTagContent (String txt, String tagName){
		String openTag = "<"+tagName+">";
		String closeTag = "</"+tagName+">";
		int start = txt.indexOf(openTag);
		int end = txt.indexOf(closeTag);
		if (start < 0 || end < 0) {
			cur=-1;
			return "";
		}
		start += openTag.length();
		cur = end+closeTag.length();
		return txt.substring(start, end);
	}
	ArrayList<ArrayList<String>> allParsed() {
		return all;
	}
	String removeTags (String html){
		int aStart=html.indexOf("href=&quot;");
		if (aStart >=0) {
			int aEnd=html.indexOf("&quot;&gt;[link]");
			curLink=html.substring(aStart+11, aEnd).replace("&amp;", "&");
		}
		html = html.replace("&lt;br&gt;", "<br>");
		html = html.replace("&lt;p&gt;", "<p>");
		
		//html = html.replace("[link]", "");
		while(true) {
			int start = html.indexOf("&lt;");
			int end = html.indexOf("&gt;");
			if (start < 0 || end < 0) break;
			String htmlL=html.substring(0,start);
			//System.out.println(html.substring(start, start+5));
			//if (html.substring(start, start+5).equals("&lt;a")) htmlL+=link;
			String htmlR=html.substring(end+4);
			html=htmlL+htmlR;
		}
		while (html.charAt(0)==' ') html = html.substring(1);
		return html;
	}
	String addPluses (String txt) {
		txt  = txt.replace("+", "%2B");
		return txt.replace(' ', '+');
	}
}
